package org.zwy.gradetrack.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.zwy.gradetrack.entity.Graduate;
import org.zwy.gradetrack.entity.Major;
import org.zwy.gradetrack.mapper.GraduateMapper;
import org.zwy.gradetrack.service.GraduateService;
import org.zwy.gradetrack.service.MajorService;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 毕业生服务实现类
 */
@Service
public class GraduateServiceImpl extends ServiceImpl<GraduateMapper, Graduate> implements GraduateService {

    @Autowired
    private MajorService majorService;

    @Override
    public Page<Graduate> pageGraduates(Integer current, Integer size, String name, Integer majorId) {
        LambdaQueryWrapper<Graduate> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(name)) {
            wrapper.like(Graduate::getName, name);
        }
        if (majorId != null) {
            wrapper.eq(Graduate::getMajorId, majorId);
        }
        wrapper.orderByDesc(Graduate::getCreateTime);
        return page(new Page<>(current, size), wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createGraduate(Graduate graduate) {
        // 检查学号是否已存在
        LambdaQueryWrapper<Graduate> studentIdWrapper = new LambdaQueryWrapper<>();
        studentIdWrapper.eq(Graduate::getStudentId, graduate.getStudentId());
        if (count(studentIdWrapper) > 0) {
            throw new RuntimeException("学号已存在");
        }

        // 检查专业是否存在
        if (graduate.getMajorId() != null) {
            Major major = majorService.getById(graduate.getMajorId());
            if (major == null) {
                throw new RuntimeException("专业不存在");
            }
        }

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        graduate.setCreateTime(now);
        graduate.setUpdateTime(now);

        return save(graduate);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateGraduate(Graduate graduate) {
        // 检查毕业生是否存在
        Graduate existingGraduate = getById(graduate.getId());
        if (existingGraduate == null) {
            throw new RuntimeException("毕业生不存在");
        }

        // 检查学号是否与其他毕业生重复
        if (!existingGraduate.getStudentId().equals(graduate.getStudentId())) {
            LambdaQueryWrapper<Graduate> studentIdWrapper = new LambdaQueryWrapper<>();
            studentIdWrapper.eq(Graduate::getStudentId, graduate.getStudentId())
                            .ne(Graduate::getId, graduate.getId());
            if (count(studentIdWrapper) > 0) {
                throw new RuntimeException("学号已存在");
            }
        }

        // 检查专业是否存在
        if (graduate.getMajorId() != null) {
            Major major = majorService.getById(graduate.getMajorId());
            if (major == null) {
                throw new RuntimeException("专业不存在");
            }
        }

        // 设置更新时间
        graduate.setUpdateTime(LocalDateTime.now());

        return updateById(graduate);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteGraduate(Integer id) {
        // 检查毕业生是否存在
        if (getById(id) == null) {
            throw new RuntimeException("毕业生不存在");
        }
        return removeById(id);
    }

    @Override
    public Graduate getGraduateById(Integer id) {
        Graduate graduate = getById(id);
        if (graduate == null) {
            throw new RuntimeException("毕业生不存在");
        }
        return graduate;
    }

    @Override
    public List<Graduate> getGraduatesByName(String name) {
        LambdaQueryWrapper<Graduate> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(Graduate::getName, name);
        wrapper.orderByDesc(Graduate::getCreateTime);
        return list(wrapper);
    }

    @Override
    public List<Graduate> getGraduatesByMajorId(Integer majorId) {
        LambdaQueryWrapper<Graduate> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Graduate::getMajorId, majorId);
        wrapper.orderByDesc(Graduate::getCreateTime);
        return list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean batchImport(List<Graduate> graduates) {
        if (graduates == null || graduates.isEmpty()) {
            throw new RuntimeException("导入数据不能为空");
        }

        // 检查学号是否重复
        Set<String> existingStudentIds = list().stream()
                .map(Graduate::getStudentId)
                .collect(Collectors.toSet());

        for (Graduate graduate : graduates) {
            if (existingStudentIds.contains(graduate.getStudentId())) {
                throw new RuntimeException("学号已存在：" + graduate.getStudentId());
            }
            // 检查专业是否存在
            if (graduate.getMajorId() != null) {
                Major major = majorService.getById(graduate.getMajorId());
                if (major == null) {
                    throw new RuntimeException("专业不存在：ID " + graduate.getMajorId());
                }
            }
        }

        // 设置创建和更新时间
        LocalDateTime now = LocalDateTime.now();
        graduates.forEach(graduate -> {
            graduate.setCreateTime(now);
            graduate.setUpdateTime(now);
        });

        return saveBatch(graduates);
    }

    @Override
    public List<Graduate> getAllGraduates() {
        return list(new LambdaQueryWrapper<Graduate>().orderByDesc(Graduate::getCreateTime));
    }
} 